﻿using FluentNHibernate.Cfg;
using NHibernate;
using NHibernate.SqlCommand;
using NHibernate.Tool.hbm2ddl;
using System.Diagnostics;

namespace Endos.Wodo.Persistence
{
    internal class DataInitializer : IDataInitializer
    {
        protected static readonly ISessionFactory _sessionFactory;

        public ISession Session { get; private set; }

        static DataInitializer()
        {
            var configuration = GetConfiguration();

            #if DEBUG
            configuration = configuration.ExposeConfiguration(e =>
            {
                e.SetInterceptor(new SqlInterceptor());
            });
            #endif

            _sessionFactory = configuration.BuildSessionFactory();
        }

        private static FluentConfiguration GetConfiguration()
        {
            return null;
            //return Fluently.Configure().Database(OracleDataClientConfiguration.Oracle10
            //                                                                  .Provider<DriverConnectionProvider>()
            //                                                                  .Dialect<GemmiusOracleDialect>()
            //                                                                  .Driver<DevartOracleDriver>()
            //                                                                  .ConnectionString(
            //                                                                      c =>
            //                                                                      c.FromConnectionStringWithKey(
            //                                                                          "DefaultConnection")))
            //               .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()));
        }

        public void GenerateSchema(string filePath, string delimiter)
        {
            var schemaExport = new SchemaExport(GetConfiguration().BuildConfiguration());

            if (!string.IsNullOrEmpty(delimiter))
                schemaExport.SetDelimiter(delimiter);

            schemaExport.SetOutputFile(filePath);
            schemaExport.Execute(true, false, false);
        }

        public void Dispose()
        {
            Session.Dispose();
        }

        private class SqlInterceptor : EmptyInterceptor
        {
            public override SqlString OnPrepareStatement(SqlString sql)
            {
                Debug.WriteLine("SQL: {0}", sql);
                return sql;
            }
        }
    }
}
